from flask import Flask, request, jsonify, app
import json
from datetime import datetime
import uuid
import requests


# Ollama配置
OLLAMA_BASE_URL = "http://localhost:11434"
OLLAMA_MODEL = "qwen3:4b"



# 检查Ollama服务是否可用
def check_ollama_available():
    """检查Ollama服务是否可用"""
    try:
        response = requests.get(f"{OLLAMA_BASE_URL}/api/tags", timeout=5)
        return response.status_code == 200
    except requests.exceptions.RequestException as e:
        print(f"Ollama服务检查失败: {str(e)}")
        return False


def generate_with_ollama(prompt):
    """使用Ollama生成题目"""
    try:
        payload = {
            "model": OLLAMA_MODEL,
            "prompt": prompt,
            "stream": False,
            "options": {
                "temperature": 0.7,
                "top_p": 0.9,
                "max_tokens": 4000
            }
        }

        print(f"调用Ollama生成题目，模型: {OLLAMA_MODEL}")
        response = requests.post(
            f"{OLLAMA_BASE_URL}/api/generate",
            json=payload,

        )

        if response.status_code == 200:
            result = response.json()
            print("Ollama生成成功")
            return result.get("response", "")
        else:
            print(f"Ollama API错误: {response.status_code} - {response.text}")
            return None

    except requests.exceptions:
        return None
    except Exception as e:
        print(f"调用Ollama失败: {str(e)}")
        return None


def parse_ai_response(response_text):
    """解析AI模型的返回结果"""
    try:
        # 清理响应文本，提取JSON部分
        cleaned_text = response_text.strip()
        print(f"AI响应原始文本: {cleaned_text[:200]}...")

        # 查找JSON开始和结束位置
        start_idx = cleaned_text.find('{')
        end_idx = cleaned_text.rfind('}') + 1

        if start_idx != -1 and end_idx != 0:
            json_str = cleaned_text[start_idx:end_idx]
            data = json.loads(json_str)

            # 验证数据结构
            if "questions" in data and isinstance(data["questions"], list):
                print(f"成功解析 {len(data['questions'])} 道题目")
                return data

        print("JSON解析失败，使用备用数据")
        return {"questions": []}

    except json.JSONDecodeError as e:
        print(f"JSON解析失败: {str(e)}")
        return {"questions": []}


def identify_questions_from_text(text_content):
    """使用AI模型识别文本中的试题"""
    try:
        prompt = f"""请分析以下文本内容，识别出其中的试题，并按指定格式返回。

文本内容：
{text_content}

请严格按照以下JSON格式返回识别结果：
{{
  "exam_name": "识别出的试卷名称",
  "subject": "学科",
  "total_score": 100,
  "time_limit": 120,
  "questions": [
    {{
      "type": "题型(single_choice/multiple_choice/true_false/fill_blank/short_answer/calculation)",
      "question": "题目内容",
      "options": ["选项A", "选项B", "选项C", "选项D"],  # 选择题需要，其他题型为null
      "answer": "正确答案",
    }}
  ]
}}

要求：
1. 准确识别题目类型
2. 如果是选择题，提取所有选项
3. 试卷名称根据内容自动生成
4. 学科根据内容判断

现在开始识别："""

        print("调用AI模型识别试题...")
        ai_response = generate_with_ollama(prompt)

        if ai_response:
            result = parse_ai_response(ai_response)

            # 转换数据结构以匹配前端期望的格式
            if "questions" in result and isinstance(result["questions"], list):
                # 按题型分类并转换格式
                questions_by_type = {
                    "选择题": [],
                    "多选题": [],
                    "填空题": [],
                    "简答题": []
                }

                # 题型映射关系
                type_mapping = {
                    "single_choice": "选择题",
                    "multiple_choice": "多选题",
                    "fill_blank": "填空题",
                    "short_answer": "简答题"
                }

                for q_type, chinese_type in type_mapping.items():
                    # 收集对应类型的题目
                    type_questions = [q for q in result["questions"] if q.get("type") == q_type]

                    # 转换格式并添加题号
                    for idx, question in enumerate(type_questions, 1):
                        formatted_question = {
                            "题号": str(idx),
                            "题目": question.get("question", ""),
                            "正确答案": question.get("answer", "")
                        }

                        # 处理选项（选择题和多选题）
                        if q_type in ["single_choice", "multiple_choice"]:
                            options = question.get("options", [])
                            formatted_options = {}
                            for i, opt in enumerate(options[:4]):  # 最多取4个选项
                                formatted_options[chr(65 + i)] = opt  # A, B, C, D
                            formatted_question["选项"] = formatted_options

                        questions_by_type[chinese_type].append(formatted_question)

                # 更新结果结构
                result["questions"] = questions_by_type

            return result
        else:
            print("AI识别失败，返回空结果")
            return {
                "exam_name": "智能识别试卷",
                "subject": "未知",
                "total_score": 100,
                "time_limit": 120,
                "questions": {}
            }

    except Exception as e:
        print(f"识别试题失败: {str(e)}")
        return {
            "exam_name": "智能识别试卷",
            "subject": "未知",
            "total_score": 100,
            "time_limit": 120,
            "questions": {}
        }


def api_identify_questions():
    """智能识别试题API"""
    if request.method == 'OPTIONS':
        return '', 200

    try:
        data = request.get_json()
        text_content = data.get('text_content', '')

        if not text_content.strip():
            return jsonify({
                'success': False,
                'message': '请输入试题内容'
            }), 400

        print(f"收到智能识别请求，内容长度: {len(text_content)}")

        # 检查Ollama是否可用
        ollama_available = check_ollama_available()

        if ollama_available:
            # 使用AI模型识别
            result = identify_questions_from_text(text_content)
        else:
            print("Ollama不可用")


        # 添加元数据
        result['metadata'] = {
            'identifiedBy': 'ollama' if ollama_available else 'fallback',
            'model': OLLAMA_MODEL if ollama_available else 'fallback',
            'timestamp': datetime.now().isoformat(),
            'contentLength': len(text_content),
            'questionCount': sum(len(questions) for questions in result.get('questions', {}).values())
        }
        print(result)
        return jsonify({
            'success': True,
            'exam_info': result
        })

    except Exception as e:
        print(f"智能识别API失败: {str(e)}")
        return jsonify({
            'success': False,
            'message': f'识别失败: {str(e)}'
        }), 500